#include <stdio.h>
#include <stddef.h>

// 定义字段描述结构体
typedef struct {
    const char *name;  // 字段名称
    size_t offset;     // 字段在结构体中的偏移量
    size_t size;       // 字段的大小
} FieldInfo;

// 定义宏简化字段描述的定义
#define FIELD_INFO(type, field) {#field, offsetof(type, field), sizeof(((type *)0)->field)}

// 通用的打印结构体字段及其内容的字节的函数
void printStructFields(const void *structPtr, const FieldInfo *fields, size_t numFields) {
    for (size_t i = 0; i < numFields; i++) {
        const FieldInfo *field = &fields[i];
        const unsigned char *fieldPtr = (const unsigned char *)structPtr + field->offset;

        printf("Field: %-10s, Offset: %2zu, Size: %2zu, Bytes: ", field->name, field->offset, field->size);
        for (size_t j = 0; j < field->size; j++) {
            printf("%02x ", fieldPtr[j]);
        }
        printf("\n");
    }
}

// 示例结构体 1
typedef struct {
    int id;
    char name[20];
    float score;
} MyStruct;

// 定义 MyStruct 的字段描述数组
FieldInfo myStructFields[] = {
    FIELD_INFO(MyStruct, id),
    FIELD_INFO(MyStruct, name),
    FIELD_INFO(MyStruct, score),
};
#define MY_STRUCT_NUM_FIELDS (sizeof(myStructFields) / sizeof(myStructFields[0]))

// 示例结构体 2
typedef struct {
    double value;
    char code;
    int count;
} AnotherStruct;

// 定义 AnotherStruct 的字段描述数组
FieldInfo anotherStructFields[] = {
    FIELD_INFO(AnotherStruct, value),
    FIELD_INFO(AnotherStruct, code),
    FIELD_INFO(AnotherStruct, count),
};

#define ANOTHER_STRUCT_NUM_FIELDS (sizeof(anotherStructFields) / sizeof(anotherStructFields[0]))

int main()
{
    // 创建 MyStruct 实例并初始化
    MyStruct myStruct = {123, "Alice", 89.5f};
    printf("Printing MyStruct:\n");
    printStructFields(&myStruct, myStructFields, MY_STRUCT_NUM_FIELDS);
    printf("\n");

    // 创建 AnotherStruct 实例并初始化
    AnotherStruct anotherStruct = {3.14159, 'X', 42};
    printf("Printing AnotherStruct:\n");
    printStructFields(&anotherStruct, anotherStructFields, ANOTHER_STRUCT_NUM_FIELDS);

    return 0;
}